<template>
  <Spin :spinning="loading">
    <div class="avatar-box">
      <HUpload
        v-model:value="avatar"
        @get-data="getData"
        :disabled="!updataFlag"
        showUploadIcon
        value-field="url"
        label-field="fileName"
        title="图片上传"
        :show-file-name="false"
      >
        <template #tips>
          <div class="avatar-info">
            <h1>{{ userName }}</h1>
            <span>{{ roleNameList || '请先完善信息' }}</span>
          </div>
        </template>
      </HUpload>
    </div>
    <BasicForm @register="register" v-bind="$attrs" />
    <div class="btn-box" v-if="updataFlag">
      <Button type="primary" @click="updateProfile" :loading="loading">确认修改</Button>
      <Button @click="handleCancel(true)">取消</Button>
    </div>
  </Spin>
</template>

<script setup lang="ts">
  import { ref, nextTick } from 'vue';
  import { HUpload } from '/@/components/Upload';
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemasForm } from '../personalCenter.data';
  import { Button, Spin } from 'ant-design-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { UpdateProfileInfo } from '/@/api/admin/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep } from 'lodash-es';
  import type { UserProfile } from '/#/store';
  const $emits = defineEmits(['updata', 'success']);
  defineProps({
    updataFlag: {
      type: Boolean,
      default: false,
    },
  });

  const { createMessage } = useMessage();
  const loading = ref(false);
  const userName = ref('');

  const avatar = ref<UploadProps['fileList']>([]);
  let httpAvatar = '';
  const useUserStores = useUserStore();
  let userInfo: UserProfile;
  let roleNameList = ref<string[]>([]);
  const [register, { updateSchema, validate, resetFields, setFieldsValue }] = useForm({
    labelWidth: 0,
    baseColProps: {
      span: 12,
    },
    layout: 'vertical',
    rulesMessageJoinLabel: true,
    schemas: schemasForm((roleList) => {
      roleNameList.value = roleList
        .filter((i) => useUserStores.getRoleList.includes(i.roleId))
        .map((i) => i.roleName)
        .toString();
    }),
    showActionButtonGroup: false,
  });

  // 初始化回显

  const getSchemeasItem = () => {
    userInfo = cloneDeep(useUserStores.getUserInfo);

    userName.value = userInfo.name;
    userInfo.role = useUserStores.getRoleList;
    let formItems = schemasForm();
    setFieldsValue({ ...userInfo });
    formItems.forEach((i) => {
      i.defaultValue = userInfo[i.field];
    });
    setAvatar();
    // updateSchema(formItems);
  };
  nextTick(() => {
    getSchemeasItem();
  });

  // 确定修改
  const updateProfile = async () => {
    let values = await validate();
    if (!avatar.value!.length) createMessage.error('请上传头像');
    const params = {
      avatar: httpAvatar,
      name: values.name,
      userSex: values.userSex,
      phone: values.phone,
    };
    loading.value = true;
    try {
      await UpdateProfileInfo(params);
      await reload();
      getSchemeasItem();
      createMessage.success('更新成功');
      handleCancel(false);
    } catch (e) {
      console.log(e);
    } finally {
      loading.value = false;
    }
  };

  const setAvatar = () => {
    if (userInfo.avatar) {
      avatar.value = [{ url: userInfo.avatar, uid: 'bq1s22d', name: '头像' }];
      httpAvatar = userInfo.avatar;
    }
  };

  async function reload() {
    await useUserStores.getUserInfoAction();
  }
  const getData = (data) => {
    httpAvatar = data;
  };

  // 取消
  const handleCancel = (reset: boolean) => {
    if (reset) {
      resetFields();
      setAvatar();
    }
    getSchemeasItem();
    $emits('success');
  };

  $emits('updata', updateSchema);
</script>

<style lang="less" scoped>
  .avatar-box {
    display: flex;
    align-items: center;
    margin: 18px 0;

    .avatar-info {
      margin-left: 4px;

      transform: translateY(15px);

      h1 {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 0;
      }

      span {
        color: rgba(0, 0, 0, 0.3);
        font-size: 14px;
      }
    }
  }

  .btn-box {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .ant-btn {
      & + .ant-btn {
        margin-left: 24px;
      }
    }
  }
</style>
